package com.zone.vehicle.superapp.view.home.pay;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.saicmotor.pay.PayManager;
import com.saicmotor.pay.entity.OrderEntity;
import com.saicmotor.pay.http.Entity.appendPayRecordEntity;
import com.saicmotor.pay.http.ResultCallback;
import com.saicmotor.pay.http.request.appendPayRecordReq;
import com.zone.sdk.module.appstore.base.StoreUtils;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.entity.UserEntity;
import com.zone.vehicle.superapp.databinding.FragmentOrderSubmitBinding;
import com.zone.vehicle.superapp.model.HomeViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.utils.TimeUtil;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;

import org.apache.commons.lang3.ObjectUtils;

import java.util.LinkedList;
import java.util.List;

import static com.zone.vehicle.superapp.view.home.HomeFragment.ORDER_PAY_FRAGMENT;

public class OrderSubmitFragment extends BaseFragment {
    private static final String TAG = "OrderSubmitFragment";
    private FragmentOrderSubmitBinding binding;

    private HomeViewModel viewModel;

    private Activity activity;

    private ResultCallback<appendPayRecordEntity> callback = new ResultCallback<appendPayRecordEntity>() {

        @Override
        public void onSuccess(appendPayRecordEntity appendPayRecordEntity) {
            if (ObjectUtils.isEmpty(appendPayRecordEntity.getPayInfo())) {
                Toast.makeText(activity, "订单提交失败，支付内容未空", Toast.LENGTH_SHORT).show();
                return;
            }
            viewModel.setPayStringInfo(appendPayRecordEntity.getPayInfo());
            changePage(ORDER_PAY_FRAGMENT);
        }

        @Override
        public void onError(String errorCode, String message) {
            Log.e(TAG, "error pay order ");
            Toast.makeText(activity, "订单提交失败，网络错误", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentOrderSubmitBinding.inflate(inflater);
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(HomeViewModel.class);
        initView();
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateView();
    }

    private void initView() {
        binding.submitBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "btnBack onClick");
                onBack();
            }
        });
        binding.btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object obj;
                obj = viewModel.getPayStringInfo();
                if (ObjectUtils.isNotEmpty(obj)) {
                    changePage(ORDER_PAY_FRAGMENT);
                    return;
                }
                obj = viewModel.getOrderEntity().getValue();
                if (ObjectUtils.isEmpty(obj)) {
                    Log.d(TAG, "pay failed of order info error");
                    Toast.makeText(activity, "支付失败，找不到订单信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                OrderEntity orderEntity = (OrderEntity) obj;
                obj = viewModel.getUserEntity().getValue();
                if (ObjectUtils.isEmpty(obj)) {
                    Log.d(TAG, "pay failed of user info error");
                    Toast.makeText(activity, "支付失败，找不到用户信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                UserEntity userEntity = (UserEntity) obj;

                obj = viewModel.getCurrentOrderAppEntity();
                if (ObjectUtils.isEmpty(obj)) {
                    Log.d(TAG, "pay failed of app info error");
                    Toast.makeText(activity, "支付失败，找不到商品信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                AppDetailEntity appEntity = (AppDetailEntity) obj;
                float price = Float.parseFloat(appEntity.getProductPrice());
                appendPayRecordReq.payDetails detail = new appendPayRecordReq.payDetails();
                detail.setAmt(Float.parseFloat(orderEntity.getOrderAmt().toString()));
                detail.setProductCode("PAY_ZFB_NATIVE");
                List<appendPayRecordReq.payDetails> list = new LinkedList<>();
                list.add(detail);
                PayManager.getInstance().appendPayRecord(
                        orderEntity.getTransNo(),
                        orderEntity.getPlatformMerchId(),
                        orderEntity.getMerchOrderId(),
                        userEntity.getUserId().toString(),
                        userEntity.getNick(),
                        Float.parseFloat(orderEntity.getOrderAmt().toString()),
                        Float.parseFloat(orderEntity.getOrderAmt().toString()),
                        appEntity.getDescription(),
                        TimeUtil.getTargetTime(1000 * 30 * 60),
                        StoreUtils.PAY_SCENE,
                        list,
                        "192.168.1.4",
                        callback
                );
            }
        });
        updateView();
    }

    private void updateView() {
        AppDetailEntity o = viewModel.getCurrentOrderAppEntity();
        if (ObjectUtils.isEmpty(o)) {
            Log.d(TAG, "pay failed of app info error");
//            Toast.makeText(activity, "支付失败，找不到商品信息", Toast.LENGTH_SHORT).show();
            return;
        }
        float price = Float.parseFloat(o.getProductPrice());
        binding.textOrderSubmitPrice.setText(String.valueOf(price));
    }
}
